<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" :show-fullscreen="false" class="form-dialog" width="50%">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon icon="ep:upload-filled" size="18" style="margin-right: 5px;"></SvgIcon>
        <span>{{ dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef" label-width="100px">
      <el-alert style="margin-bottom: 10px" type="info">
        <template #title>
          <div>导入失败或者成功后需要清理导入的文件才可以重新导入</div>
          <div>导入格式：订单号 | 物流名称 | 物流编码</div>
        </template>
      </el-alert>
      <el-form-item label="导入文件：">
        <!-- 导入操作 -->
        <el-upload ref="upload"
                   :accept="accept"
                   :action="uploadUrl"
                   :auto-upload="false"
                   :before-upload="beforeFileUpload"
                   :file-list="fileList"
                   :headers="uploadHeaders"
                   :limit="1"
                   :multiple=false
                   :on-error="handleUploadError"
                   :on-progress="handleUploadProgress"
                   :on-success="handleUploadSuccess">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <div class="el-upload__tip" style="margin-left: 6px">只能上传xls/xlsx文件</div>
        </el-upload>
      </el-form-item>

      <el-alert v-if="respData.code >= 0 " :title="respData.message" :type="respData.code === 0 ? 'success' : 'error'"/>
    </el-form>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button v-permission="['goods:order:export']" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { ElLoading, ElMessage, FormInstance, UploadFile, UploadFiles, UploadProgressEvent, UploadProps, UploadRawFile } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { getRequestUrl } from '@/utils/axios/axios-service.ts';
import { getToken, getTokenHeader } from '@/utils/auth.ts';
import { AppInfoParserCallback } from '@/components/upload/src/use-upload.ts';

defineOptions({name: 'order-delivery-import-form'})

const formRef = ref<FormInstance>();
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

// 服务端上传地址
const uploadUrl = ref(getRequestUrl('/shop/order/import_shipping_data'));
// 服务端上传头部
const uploadHeaders = computed(() => {
  let headers = {};
  let header = getTokenHeader();
  if (header) {
    headers[header] = getToken();
  }
  return headers;
});
const accept = ref('.xls,.xlsx');
const fileList = ref<any[]>([]);
const loading = ref();
const respData = reactive({
  code: -1, message: ''
});

// 文件上传前校检
const beforeFileUpload = async (file: UploadRawFile, callback: AppInfoParserCallback) => {

};

// 上传成功
const handleUploadSuccess: UploadProps['onSuccess'] = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles): void => {
  if (loading.value) {
    loading.value.close();
  }
  let {message, code} = response
  respData.code = code
  respData.message = message;
  if (code > 0) {
    ElMessage.warning({message: message,});
  } else {
    emit('refresh');
    ElMessage.success({message: message,});
  }
};

// 上传异常
const handleUploadError: UploadProps['onError'] = (error: Error, uploadFile: UploadFile, uploadFiles: UploadFiles): void => {
  if (loading.value) {
    loading.value.close();
  }
  ElMessage.warning({message: '上传文件异常错误',});
};

// 上传进度
const handleUploadProgress: UploadProps['onProgress'] = (evt: UploadProgressEvent, uploadFile: UploadFile, uploadFiles: UploadFiles): void => {
  if (!loading.value) {
    loading.value = ElLoading.service({
      lock: true,
      text: '正在导入物流数据中...',
      background: 'rgba(0, 0, 0, 0.2)'
    });
  }
};

/** 打开弹窗 */
const open = async (data: any) => {
  dialogTitle.value = '订单物流数据导入';
  dialogVisible.value = true;
  // 重置表单
  handleFormReset();
}
// 提供 open 方法，用于打开弹窗
defineExpose({open});

/** 表单提交 */
const emit = defineEmits(['refresh']);
const upload = ref();
const onSubmitForm = async () => {
  upload.value?.submit()
};

/** 重置表单 */
const handleFormReset = () => {
  respData.code = -1;
  respData.message = '';
  loading.value = undefined;
  fileList.value = [];
  // 重置界面表单数据
  formRef.value?.resetFields();
};

</script>

<style lang="scss" scoped>

</style>
